from django.contrib.auth.models import User
from django.db import models

from utils.modelsMixin import DateTimeModelMixin, ModelMixin


# Create your models here.

# 标签表
class Label(DateTimeModelMixin):
    name = models.CharField(max_length=100, unique=True, verbose_name="标签名")

    class Meta:
        db_table = "label"

    def __str__(self):
        return self.name


# 文章表
# 文章和标签之间是可以存在  一对多 or  多对多
# 文章和用户 一对多或者  一对一
class Article(ModelMixin):
    STATUS_CHOICES = ((0, "未发布"), (1, "发布"))
    title = models.CharField(max_length=100, unique=True, verbose_name="标题")
    digest = models.CharField(max_length=300, verbose_name="摘要")
    content = models.TextField(verbose_name="内容")
    page_view = models.IntegerField(default=0, verbose_name="浏览量")
    priority = models.IntegerField(default=0, verbose_name="优先级")
    status = models.IntegerField(default=0, verbose_name="状态", choices=STATUS_CHOICES)
    # 正向查询 Article.label.name    # 反向查询  Label.article_set.title
    label = models.ForeignKey(Label, on_delete=models.SET_NULL, null=True, verbose_name="标签")
    user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="作者")

    class Meta:
        db_table = "article"
        # 排序规则
        ordering = ["-priority", "-page_view", "-created_time"]

    def __str__(self):
        return f"作者：{self.user.username}.文章{self.title}"


# 评论模型
class Comment(ModelMixin):
    content = models.TextField(verbose_name="评论内容")
    article = models.ForeignKey(Article, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    # 父级评论  外键字段的产生
    # 正向 Comment.parent_comment     #反向查询  Comment.parent_comment_set  自定义管理器名
    parent_comment = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE, verbose_name="父级评论",
                                       related_name="parent_comment_set")
    # 子级评论 回复了谁  外键字段的产生
    # 正向 Comment.reply_comment     #反向查询  Comment.reply_comment_set
    reply_comment = models.ForeignKey("self", null=True, blank=True, on_delete=models.CASCADE, verbose_name="回复评论",
                                      related_name="reply_comment_set")

    class Meta:
        db_table = "comment"
        # 最新发布的时间来进行排序
        ordering = ["-created_time"]

    def __str__(self):
        return f"用户{self.user.username}:{self.content}"
